<?php

class GalactusModelTelescope extends GalactusModel {

	function __construct($control) {
		GalactusModel::__construct($control);
	}

	public function add($name, $model_id, $link_control, $link_camera, $brief, $image, $image_type) {
		$image_type = end(explode("/", $image_type));
		if(empty($image)) {
			$image = "images/telescope-unknown.png";
			$image_type = "png";
		}
		$sql = "INSERT INTO Telescope (name, image, image_type, model_id, link_control, link_camera, brief) VALUES (:name, :image, :image_type, :model_id, :link_control, :link_camera, :brief)";
		$params = array(
			":name" => $name,
			":model_id" => $model_id,
			":link_control" => $link_control,
			":link_camera" => $link_camera,
			":brief" => $brief,
			":image" => file_get_contents($image),
			":image_type" => $image_type
		);
		$query = $this->query($sql, $params);
		if($query["fail"])
			throw new Exception("Falha ao adicionar telescópio!");
		$this->generateSettings( );
		$this->control->view->helper->alertSuccess("Telescópio inserido com sucesso!", URL.'REDIRECT/TELESCOPE/SHOW');
	}

	public function edit($telescope_id, $name, $model_id, $link_control, $link_camera, $brief, $image, $image_type) {
		$sql = "";
		$params = array(
			":id" => $telescope_id,
			":name" => $name,
			":model_id" => $model_id,
			":link_control" => $link_control,
			":link_camera" => $link_camera,
			":brief" => $brief
		);
		if(!empty($image)) {
			$sql = "image = :image, image_type = :image_type,";
			$params[":image"] = file_get_contents($image);
			$params[":image_type"] = end(explode("/", $image_type));
		}
		$sql = "UPDATE Telescope SET id = :id, ".$sql." name = :name, model_id = :model_id, link_control = :link_control, link_camera = :link_camera, brief = :brief WHERE id = :id";
		$query = $this->query($sql, $params);
		if($query["fail"])
			throw new Exception("Falha ao alterar telescópio!");
		$this->generateSettings( );
		$this->control->view->helper->alertSuccess("Telescópio alterado com sucesso!", URL.'REDIRECT/TELESCOPE/SHOW');
	}

	public function remove($telescope_id) {
		$query = $this->query("DELETE FROM Telescope WHERE id = :id", array(":id" => $telescope_id));
		if($query["fail"])
			throw new Exception("Falha ao remover telescópio!");
		$this->generateStreamingServerSettings( );
		$this->control->view->helper->alertSuccess("Telescópio removido com sucesso!", URL.'REDIRECT/TELESCOPE/SHOW');
	}

	public function retrieveTelescope($param = NULL) {
		$sql = "
			SELECT t.id AS telescope_id, t.name, t.image, t.image_type, t.link_camera, t.link_control, t.brief, tm.id AS model_id, tm.model, tm.link_maker
			FROM Telescope t
			INNER JOIN TelescopeModel AS tm ON t.model_id = tm.id
			".((!empty($param))? "WHERE t.id = :param OR t.name = :param" : NULL)."
			ORDER BY name
		";
		$query = $this->query($sql, array(":param" => $param));
		if(!$query["fail"])
			return $query["result"];
		return NULL;
	}

	public function retrieveTelescopeModels( ) {
		$query = $this->query("SELECT * FROM TelescopeModel ORDER BY model");
		if(!$query["fail"] && !empty($query["result"]))
			return $query["result"];
		else throw new Exception("Falha ao recuperar informações dos modelos dos telescópios!");
	}

	public function start( ) {
		$this->stop( );
		$telescopes = $this->control->model->retrieveTelescope( );
		for($i = 0; $i < count($telescopes); ++$i) {
			$cmd .= ' -i '.$telescopes[$i]["link_camera"].' -vcodec copy http://'.$_SERVER["HTTP_HOST"].':8090/feed'.$telescopes[$i]["telescope_id"].'.ffm';
		}
		$cmd = 'ffserver -f /var/www/galactus/ffserver.conf >/dev/null 2>/dev/null & ffmpeg '.$cmd.' >/dev/null 2>/dev/null &';
		shell_exec($cmd);
	}

	public function stop( ) {
		exec("pgrep ffserver", $pids);
		if(!empty($pids))
			posix_kill($pids[0], 9);
	}

	private function generateSettings( ) {
		$ffserver = "
			Port 8090
			BindAddress 0.0.0.0
			MaxHTTPConnections 2000
			MaxClients 1000
			MaxBandwidth 1000
			NoDaemon
		";
		$telescopes = $this->retrieveTelescope( );
		for($i = 0; $i < count($telescopes); ++$i) {
			$ffserver .= "
				<Feed feed".$telescopes[$i]["telescope_id"].".ffm>
					File /tmp/feed".$telescopes[$i]["telescope_id"].".ffm
					FileMaxSize 50M
				</Feed>
				<Stream camera".$telescopes[$i]["telescope_id"].".mjpeg>
					Feed feed".$telescopes[$i]["telescope_id"].".ffm
					Format mpjpeg
					VideoFrameRate 15
					VideoBitRate 128
					VideoBufferSize 40000
					VideoQMin 1
					VideoQMax 5
					VideoSize 640x480
					VideoIntraOnly
					NoAudio
					Strict -1
				</Stream>
			"; 
		}
		file_put_contents("/var/www/galactus/ffserver.conf", $ffserver);
		$this->start( );
	}

}

?>
